#include "MotorDriver.h"
#include "wk_system.h"

/*
初始化定时器等外设，初始化相关参数
*/
uint8_t MotorDriver_Init(void)
{
    return 0;
}

/*
根据pwm参数和供电电压参数，将电压值转为pwm占空比，并更新到寄存器
phase: 电机的ABC相
voltage: 电机的电压 0 - 1.0
*/
uint8_t MotorDriver_set_volatge(uint8_t phase, float voltage)
{
    uint16_t pwm_value;
    tmr_channel_select_type tmr_channel;

    if (phase > MOTOR_PHASE_C)
        return 1;

    /**/ if (phase == MOTOR_PHASE_A)
        tmr_channel = TMR_SELECT_CHANNEL_1;
    else if (phase == MOTOR_PHASE_B)
        tmr_channel = TMR_SELECT_CHANNEL_2;
    else if (phase == MOTOR_PHASE_C)
        tmr_channel = TMR_SELECT_CHANNEL_3;

    if (voltage > 1.0f)
        voltage = 1.0f;
    if (voltage < 0.0f)
        voltage = 0.0f;
    pwm_value = (uint16_t)((float)MOTOR_MAX_PWM_VALUE * voltage);
    if (pwm_value > MOTOR_MAX_PWM_VALUE)
        pwm_value = MOTOR_MAX_PWM_VALUE;

    tmr_channel_value_set(TMR1, tmr_channel, pwm_value);

    return 0;
}

uint8_t MotorDriver_set_volatge_three(float Va, float Vb, float Vc)
{
    MotorDriver_set_volatge(MOTOR_PHASE_A, Va);
    MotorDriver_set_volatge(MOTOR_PHASE_B, Vb);
    MotorDriver_set_volatge(MOTOR_PHASE_C, Vc);
    return 0;
}
